package xmltomce.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;



public class FileDialog{
	
	private File selectedFile;
	private JFileChooser fileChooser;
	private JLabel fileLabel;
	private JButton fileSelectButton;
	
	
	
	public FileDialog(File preSelectedFile){
		setPreSelectedFile(preSelectedFile);
	}
	
	public FileDialog(String preSelectedFilePath){
		File selectedFile = new File(preSelectedFilePath);
		setPreSelectedFile(selectedFile);
	}
	
	private void setPreSelectedFile(File preSelectedFile){
		if (preSelectedFile.exists() || preSelectedFile.isDirectory()){
			selectedFile = preSelectedFile;
		}else{
			selectedFile = new File(System.getProperty("user.home"));
		}
	}
	
	public JFileChooser getFileChooser(){
		if (fileChooser == null){
			fileChooser = new JFileChooser(selectedFile);
		}
		return fileChooser;
	}
	
	public JLabel getFileLabel(){
		if (fileLabel == null){
			fileLabel = new JLabel();
			fileLabel.setBorder(BorderFactory.createTitledBorder(""));
			visualizeFilePath();
		}
		return fileLabel;
	}
	
	public JButton getFileSelectButton(){
		if (fileSelectButton == null){
			fileSelectButton = new JButton("Select");
			fileSelectButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					showSelectFileDialog();
				}
			});
		}
		return fileSelectButton;
	}
	
	public void showSelectFileDialog(){
		int returnValue = getFileChooser().showOpenDialog(null);
		if (returnValue == JFileChooser.APPROVE_OPTION){
			selectedFile = getFileChooser().getSelectedFile();
			visualizeFilePath();
		}
	}
	
	private void visualizeFilePath(){
		getFileLabel().setText(selectedFile.getAbsolutePath());
	}
	
	public File getSelectedFile(){
		return selectedFile;
	}
	
}
